package com.jqr.activity.fragmentmanagerdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.jqr.activity.fragmentmanagerdemo.fragments.CommunityFragment;
import com.jqr.activity.fragmentmanagerdemo.fragments.IFragmentCallback;
import com.jqr.activity.fragmentmanagerdemo.fragments.IndexFragment;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnChangeCommunity=findViewById(R.id.btnChangeCommunity);

        btnChangeCommunity.setOnClickListener(this);

        Button btnChangIndex= findViewById(R.id.btnChangIndex);

        btnChangIndex.setOnClickListener(this);


    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager=getSupportFragmentManager();
        FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container_host,fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case (int)R.id.btnChangIndex:

                Bundle bundle=new Bundle();
                bundle.putString("message","IndexFragment");
                IndexFragment indexFragment=new IndexFragment();
                indexFragment.setArguments(bundle);
                indexFragment.setCallback(new IFragmentCallback() {
                    @Override
                    public void sendMsgToActivity(String str) {
                        Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public String getMsgFromActivity(String str) {
                        return null;
                    }
                });
                replaceFragment(indexFragment);
                break;
            case  R.id.btnChangeCommunity:
                replaceFragment(new CommunityFragment());
                break;
        }
    }
}